﻿using System;
using System.Collections.Generic;
using System.Linq;
using Loki;
using Luna.Model.Project;

namespace Luna.UI.Project
{
    public class ProjectMonthlyCostGraphViewModel : ProjectGraph
    {
        private LokiCollection<GraphPoint<DateTime, decimal>> _SourcePoints;

        public override object DataSource
        {
            get { return _SourcePoints; }
        }

        public ProjectMonthlyCostGraphViewModel()
        {
            _SourcePoints = new LokiCollection<GraphPoint<DateTime, decimal>>();
        }

        protected override void ReloadGraph(object P_Sender, EventArgs e)
        {
            if (ProjectID.HasValue)
            {
                IProject L_Project = ApplicationModel.Project.Projects[ProjectID.Value];
                _SourcePoints.Clear();

                List<GraphPoint<DateTime, decimal>> L_FilteredList = new List<GraphPoint<DateTime, decimal>>();

                foreach (var L_Account in ApplicationModel.Accounting.Accounts)
                {
                    foreach (var L_Operation in L_Account.Operations.Where(x => x.ExecutionDate >= StartDate && x.ExecutionDate < EndDate && x.Project != null && x.Project.ID == L_Project.ID))
                    {
                        L_FilteredList.Add(new GraphPoint<DateTime, decimal>() { Argument = L_Operation.ExecutionDate, Value = -L_Operation.Amount });
                    }
                }

                foreach (var L_MonthOperations in L_FilteredList.GroupBy(x => new DateTime(x.Argument.Year, x.Argument.Month, 1)))
                {
                    _SourcePoints.Add(new GraphPoint<DateTime, decimal>()
                    {
                        Argument = L_MonthOperations.Key,
                        Value = L_MonthOperations.Sum(x => x.Value)
                    });
                }
            }
        }
    }
}
